package com.googlecode.garbagecan.configuration.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

public class XmlConfigurationExample {
	
	public static void main(String[]args) throws Exception {
		testLoadFromURL();
		testSelect();
	}

	private static void testLoadFromURL() throws ConfigurationException {
		// load from url
		URL url = XmlConfigurationExample.class.getResource("/com/googlecode/garbagecan/configuration/xml/example.xml");
		XMLConfiguration xmlConf = null; 
		xmlConf = new XMLConfiguration(url);
		print(xmlConf);
		
		// load from file
		xmlConf = new XMLConfiguration(url.getFile());
		print(xmlConf);
		
		// load from file
		xmlConf = new XMLConfiguration();
		xmlConf.load(url.getFile());
		print(xmlConf);
		
		// load from Reader
		String s = "<myconfig></myconfig>";
		xmlConf = new XMLConfiguration();
		xmlConf.load(new InputStreamReader(new ByteArrayInputStream(s.getBytes())));
		print(xmlConf);
	}
	
	private static void testSelect() throws ConfigurationException {
		File file = new File(XmlConfigurationExample.class.getResource("example.xml").getFile());
		XMLConfiguration xmlConf = new XMLConfiguration(file);
		String[] arr = xmlConf.getStringArray("users.user.username");
		print(arr[0]);
		print(arr[1]);
		print(arr[2]);
		
		List list = xmlConf.getList("users.user"); 
		print("select list: " + list);
	}
	private static void print(Object obj) {
		System.out.println(obj);
	}
}
